package com.ruoyi.shop.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.ruoyi.common.security.annotation.InnerAuth;
import com.ruoyi.order.api.domain.Order;
import com.ruoyi.service.api.domain.CheService;
import com.ruoyi.shop.api.domain.CheDrawal;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.shop.api.domain.CheShop;
import com.ruoyi.shop.service.ICheShopService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

import static com.ruoyi.common.core.web.domain.AjaxResult.DATA_TAG;

/**
 * 门店管理Controller
 * 
 * @author ruoyi
 * @date 2024-12-31
 */
@RestController
@RequestMapping("/shop")
public class CheShopController extends BaseController
{
    @Autowired
    private ICheShopService cheShopService;


    /**
     * 查询门店管理列表
     */
    @RequiresPermissions("shop:shop:list")
    @GetMapping("/list")
    public TableDataInfo list(CheShop cheShop)
    {
        startPage();
        List<CheShop> list = cheShopService.selectCheShopList(cheShop);
        return getDataTable(list);
    }
//根据手机号查询 登录使用
@GetMapping("/phone/{phone}")
public AjaxResult listbyphone(@PathVariable("phone") String  phone)
{
    CheShop cheShop = cheShopService.selectCheShopByPhone(phone);
    return AjaxResult.success(cheShop);
}

    @RequiresPermissions("shop:shop:list")
    @GetMapping("/list1")
    public TableDataInfo list1()
    {
        List<CheShop> list = cheShopService.selectCheShopList1();
        return getDataTable(list);
    }
    /**
     * 查询门店排行列表
     */
    @RequiresPermissions("shop:shop:list")
    @GetMapping("/listByStar")
    public TableDataInfo listByStar(CheShop cheShop)
    {
        startPage();
        List<CheShop> list = cheShopService.selectCheShopListByStar(cheShop);
        return getDataTable(list);
    }


    /**
     * 导出门店管理列表
     */
    @RequiresPermissions("shop:shop:export")
    @Log(title = "门店管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CheShop cheShop)
    {
        List<CheShop> list = cheShopService.selectCheShopList(cheShop);
        ExcelUtil<CheShop> util = new ExcelUtil<CheShop>(CheShop.class);
        util.exportExcel(response, list, "门店管理数据");
    }

    /**
     * 获取门店管理详细信息
     */
//    @RequiresPermissions("shop:shop:query")
//    @InnerAuth  // 内部鉴权
    @GetMapping(value = "/{shopId}")
    public AjaxResult getInfo(@PathVariable("shopId") Long shopId)
    {
       if(cheShopService.selectCheShopByShopId(shopId) == null){
           return AjaxResult.error();
       }else {
           return success(cheShopService.selectCheShopByShopId(shopId));
       }
    }

    /**
     * 新增门店管理
     */
//    @RequiresPermissions("shop:shop:add")
    @Log(title = "门店管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CheShop cheShop)
    {
        return toAjax(cheShopService.insertCheShop(cheShop));
    }


    /**
     * 修改门店管理
     */
    @RequiresPermissions("shop:shop:edit")
    @Log(title = "门店管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CheShop cheShop)
    {
        return toAjax(cheShopService.updateCheShop(cheShop));
    }

    /**
     * 删除门店管理
     */
    @RequiresPermissions("shop:shop:remove")
    @Log(title = "门店管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{shopIds}")
    public AjaxResult remove(@PathVariable Long[] shopIds)
    {
        return toAjax(cheShopService.deleteCheShopByShopIds(shopIds));
    }

    /**
     * 监听支付提交，改变商家余额
     * RabbitMQ实现异步操作
     * @param message
     */
    @RabbitListener(queues = "order_queue_shop")
    public void myListener1(Message message){
        //队列中的消息体Order对象
        String jsonOrder = new String(message.getBody());
        System.out.println("消费者接收到的消息为：" + jsonOrder);
        Gson gson = new Gson();
        MessageProperties messageProperties = message.getMessageProperties();
        //队列中的消息头，messageProperties得到鉴权需要的Authorization
        String authorization = messageProperties.getHeader("Authorization");
        Order order = gson.fromJson(jsonOrder, Order.class);
        System.out.println("对象解析："+order);
        //通过订单获取对应商家的信息
        CheShop cheShop = cheShopService.selectCheShopByShopId(order.getShopId());
        //TODO
        //收入入账
        Double accIncome = cheShop.getAccIncome();
        accIncome += order.getRealPrice();
        cheShop.setAccIncome(accIncome);
        Double money = cheShop.getShopMoney();
        money += order.getRealPrice();
        cheShop.setShopMoney(money);
        cheShopService.updateCheShop(cheShop);
    }

    /**
     * 监听提现，改变商家余额
     * RabbitMQ实现异步操作
     * @param message
     */
    @RabbitListener(queues = "drawal_queue_shop")
    public void myListener2(Message message) throws Exception {
        //队列中的消息体Order对象
        String jsonDrawal = new String(message.getBody());
        System.out.println("消费者接收到的消息为：" + jsonDrawal);
        Gson gson = new Gson();
        MessageProperties messageProperties = message.getMessageProperties();
        //队列中的消息头，messageProperties得到鉴权需要的Authorization
        String authorization = messageProperties.getHeader("Authorization");
        CheDrawal cheDrawal = gson.fromJson(jsonDrawal, CheDrawal.class);
        System.out.println("对象解析："+cheDrawal);
        //通过订单获取对应商家的信息
        CheShop cheShop = cheShopService.selectCheShopByShopId(cheDrawal.getShopId());
        //收入出账
        //判断余额是否够
        Double money = cheShop.getShopMoney();
        Double accOut = cheShop.getAccOut();
        if(money >= cheDrawal.getDrawalMoney()){
            accOut += cheDrawal.getDrawalMoney();
            cheShop.setAccOut(accOut);
            money -= cheDrawal.getDrawalMoney();
            cheShop.setShopMoney(money);
            cheShopService.updateCheShop(cheShop);
        }else {
            throw new Exception("余额不足");
        }
    }
}
